<?php

namespace app\admin\controller\goods;

use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 商品分类
 *
 * @icon fa fa-circle-o
 */
class Category extends Backend
{

    /**
     * Category模型对象
     * @var \app\admin\model\goods\Category
     */
    protected $model = null;
    protected $noNeedRight = ['selectpage'];
    protected $searchFields = 'name';


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\goods\Category;

//        $this->model = $this->model->where('del',0)->order('weigh desc, id desc')->select();
        $categorydata = [0 => ['type' => 'all', 'name' => __('顶级分类')]];

        $this->view->assign('parentList',$categorydata);
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $id     = $this->request->request('ids',0);
        if ($this->request->isAjax()) {
            $search = $this->request->request("search");
            $type   = $this->request->request("type");
            $params   = $this->request->param('filter');
            $name = json_decode($params,true);
            if (!empty($name))
            {
                $search = $name['name'];
            }

            $where = [];
            $where['del'] = ['eq',0];
            $where['pid'] = ['eq',$id];
            $categorylist = $this->model->where($where)->order('weigh desc, id desc')->select();
            //构造父类select列表选项数据
            $list = [];

            if ($search){

                foreach ($categorylist as $k => $v){

                    if ($search&&stripos($v['name'], $search) !== false) {
                        $v['name']=preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)/", " ", strip_tags($v['name'])); //过滤空格
                        $list[] = $v;
                    }
                }
            }else{
                $list = $categorylist;
            }
            $total = count($list);
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->assignconfig('category_Id',$this->request->request('ids',0));
        return $this->view->fetch();
    }
    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            $ids = $this->request->param('category_Id',0);
            $data = $this->model->get($ids);
            $this->view->assign('data',$data);
            $this->view->assign('ids',$ids);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        $is_pid = Db::name('goods_category')->where('id',$params['pid'])->find();
        $params['pids'] = $params['pid'] == 0 ? 0 : $is_pid['pids'].'-'.$is_pid['id'];

        if ($is_pid['level'] == 4)
        {
            $this->error('已经最高,无法再添加子分类');
        }else{
            $params['level'] = $is_pid['level'] + 1;
        }

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $params['create_time'] = time();
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }
    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $data = $this->model->get($row['pid']);

            $this->view->assign('data', $data);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");

        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $category = $this->model::get($ids);
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->where('del',0)->select()->toArray();
            if (!empty($list))
            {
                $arrId = $this->model->cycledel($list,$ids);
                array_push($arrId,(int)$ids);
                $count = $this->model->where('id','in',$arrId)->update([
                    'del' => 1
                ]);

            }else{
                $category->del = 1;
                $category->save();
                $count = $category->id;
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }




}
